package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


// 继承什么就是，StudentServlet就是Servlet
@WebServlet("/findAllTeacher")
public class FindAllTeacherServlet extends HttpServlet{

	// 覆盖父类的service方法，一定要选是HttpServletRequest这个service方法
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("TeacherServlet.service()");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		ArrayList<Teacher> list = new ArrayList<Teacher>();
		// 加载驱动
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "select id,name,age,salary from teacher";
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				Double salary = resultSet.getDouble("salary");
				Teacher teacher = new Teacher(id, name, salary, age);
				list.add(teacher);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		for (Teacher teacher : list) {
			System.out.println(teacher);
		}
		
		// 把查询出来的list集合放到req里面
		req.setAttribute("list", list);
		// 然后转发到/teacher_list.jsp这个页面进行展示
     	req.getRequestDispatcher("/teacher_list.jsp").forward(req, resp);
	}
}
